package com.open.capacity.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.finance.config.Globals;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.user.dao.SysConfigDao;
import com.open.capacity.user.model.SysConfig;
import com.open.capacity.user.service.SysConfigService;
import com.open.capacity.utils.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysConfigDao configDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SysConfig config) {
        config.setUpdateTime(new Date());

        configDao.updateByOps(config);

        log.info("修改配置：{}", config);
    }


    @Override
    public SysConfig findById(String id) {
        return configDao.findById(id);
    }

    @Override
    public SysConfig findByKey(String id) {
        SysConfig config = null;
        try {
            if (CollectionUtils.isNotEmpty(Globals.configList)) {
                Optional<SysConfig> op = Globals.configList.stream().filter(t -> t.getCnfKey().equals(id)).findFirst();
                if (op.isPresent()) {
                    config = op.get();
                } else {
                    config = configDao.findByKey(id);
                    Globals.configList = configDao.findAll(new HashMap<>());
                }
            } else {
                config = configDao.findByKey(id);
                Globals.configList = configDao.findAll(new HashMap<>());
            }

        } catch (Exception e) {
            log.error("获取参数配置出错", e.getMessage());
        }
        return config;
    }

    @Transactional
    @Override
    public int save(SysConfig config) {
        int i = 0;
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();

        config.setUpdateTime(new Date());
        config.setUpdateUserid(loginAppUser.getId());
        config.setUpdateUsername(loginAppUser.getRealName());
        i = configDao.save(config);

        Globals.configList = null;

        return i;
    }

    @Transactional
    @Override
    public Result saveOrUpdate(SysConfig config, String keyValue) {
        int i = 0;
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
        SysConfig model = configDao.findById(keyValue);
        if (model != null) {
            config.setId(keyValue);
            config.setUpdateTime(new Date());
            config.setUpdateUserid(loginAppUser.getId());
            config.setUpdateUsername(loginAppUser.getRealName());
            i = configDao.updateByOps(config);
        } else {
            config.setId(keyValue);
            config.setUpdateTime(new Date());
            config.setUpdateUserid(loginAppUser.getId());
            config.setUpdateUsername(loginAppUser.getRealName());
            i = configDao.save(config);
        }

        Globals.configList = null;

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public PageResult<SysConfig> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SysConfig> list = configDao.findAll(params);
        PageInfo<SysConfig> pageInfo = new PageInfo(list);

        return PageResult.<SysConfig>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

}
